package tech.mhuang.ext.netty.sample.server;

import tech.mhuang.ext.netty.vo.BaseMessage;
import tech.mhuang.ext.netty.sample.vo.TestP0802;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author mHuang
 * @version V1.0.0
 * @Description Netty 服务处理
 * @date 2015年7月16日 下午3:19:56
 */
@Sharable//注解@Sharable可以让它在channels间共享  
public class TestNettyServerHandler extends SimpleChannelInboundHandler<BaseMessage> {

    public static volatile Long countWidh = 0L;

    public Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Description 接收客户端数据后返回
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, BaseMessage msg)
            throws Exception {
        logger.info("====receive and reply client data====");
        logger.info("===receive waiting====");
        logger.info("====begin nettyServer read data ====");
        try {
            TestP0802 resp = new TestP0802();
            logger.info("====end nettyServer read data=====");
            ctx.writeAndFlush(resp);
            logger.info("===receive ok====");
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    /**
     * Description 客户端连接成功后返回
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("====client connection sucess====");
        Channel channel = ctx.channel();
        System.out.println(channel.id().asLongText());
        TestP0802 result = new TestP0802();
        byte[] hello = "你好".getBytes("gbk");
        result.setBody(hello);

        ctx.writeAndFlush(result);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                logger.info("读取数据超时~~");
            } else if (event.state() == IdleState.WRITER_IDLE) {
                logger.info("写入超时、发送心跳包！");
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * Description 异常处理
     *
     * @param ctx
     * @param cause
     * @throws Exception
     * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext, Throwable)
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        if (!ctx.isRemoved()) {
            logger.info("====here reply exception message====");
        }
        cause.printStackTrace();
        ctx.close();
    }


}
